package com.hdmp.auth.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hdmp.auth.entity.SysOrgEntity;
import com.hdmp.auth.mapper.SysOrgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author BigFan
 * @create 2018/11/18 1:42 PM
 */
@Service
public class SysOrgService {

    @Autowired
    SysOrgMapper sysOrgMapper;

    /**
     * 根据用户id获取组织信息
     *
     * @param dbid
     * @return
     */
    public List<Integer> queryOrgDbidByUserDbid(Integer dbid) {
        List<Integer> orgDbids = sysOrgMapper.queryOrgDbidByUserDbid(dbid);
        return orgDbids == null ? Lists.newArrayList() : orgDbids;
    }


    /**
     * 获取某个节点下的所有节点，以树形展示
     *
     * @param root
     * @return
     */
    public List<SysOrgEntity> queryAllOrg(Integer root) {

        List<SysOrgEntity> orgEntities = sysOrgMapper.selectList(null);

        Map<String, SysOrgEntity> allMap = Maps.newHashMap();

        orgEntities.forEach(e -> allMap.put(e.getDbid() + "", e));

        List<SysOrgEntity> rootList = orgEntities.stream()
                .filter(e -> e.getParentDbid() == root)
                .sorted((e1, e2) -> Integer.compare(e1.getOrders(), e2.getOrders()))
                .collect(Collectors.toList());

        if (rootList != null && rootList.size() > 0) {
            rootList.forEach(e -> getOrgTreeList(orgEntities, e));
        }
        return rootList == null ? Lists.newArrayList() : rootList;
    }


    public void getOrgTreeList(List<SysOrgEntity> allList, SysOrgEntity parent) {

        List<SysOrgEntity> chidlren = allList.stream()
                .filter(e -> e.getParentDbid() == parent.getDbid())
                .sorted((e1, e2) -> Integer.compare(e1.getOrders(), e2.getOrders()))
                .collect(Collectors.toList());
        if (chidlren != null && chidlren.size() > 0) {
            parent.setChildren(chidlren);
            chidlren.forEach(e -> getOrgTreeList(allList, e));
        }
    }


    public int deleteTest(Long dbid) {

        Integer del = sysOrgMapper.deleteById(dbid);
        return del;
    }


    public Integer inserOrg() {
       SysOrgEntity orgEntity = new SysOrgEntity();
       orgEntity.setDbid(5);
       orgEntity.setName("fzx22344");
       orgEntity.setVersion(1l);
        //sysOrgMapper.updateById(orgEntity);
        return sysOrgMapper.updateById(orgEntity);
    }

}
